Number of islands

Time: O(MxN); Space: O(MxN); medium

Given a 2d grid map of ’1’s (land) and ’0’s (water), count the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input: grid =

[
  ['1','1','1','1','0'],
  ['1','1','0','1','0'],
  ['1','1','0','0','0'],
  ['0','0','0','0','0']
]

Output: 1

Example 2:

Input: grid =

[
  ['1','1','0','0','0'],
  ['0','1','0','0','1'],
  ['0','0','0','1','1'],
  ['0','0','0','0','0'],
  ['0','0','0','0','1']
]

Output: 3

1. DFS [O(MxN), O(MxN)]

[9]:
class Solution1(object):
    """
    Time: O(M*N)
    Space: O(M*N)
    """
    def numIslands(self, grid):
        """
        :type grid: List[List[bool]]
        :rtype: int
        """
        if not grid:
            return 0

        row = len(grid)
        col = len(grid[0])
        count = 0
        for i in range(row):
            for j in range(col):
                if grid[i][j] == '1':
                    self.dfs(grid, row, col, i, j)
                    count += 1
        return count

    def dfs(self, grid, row, col, x, y):
        if grid[x][y] == '0':
            return
        grid[x][y] = '0'

        if x != 0:
            self.dfs(grid, row, col, x - 1, y)
        if x != row - 1:
            self.dfs(grid, row, col, x + 1, y)
        if y != 0:
            self.dfs(grid, row, col, x, y - 1)
        if y != col - 1:
            self.dfs(grid, row, col, x, y + 1)
[10]:
s = Solution1()

grid = [
  ['1','1','1','1','0'],
  ['1','1','0','1','0'],
  ['1','1','0','0','0'],
  ['0','0','0','0','0']
]
assert s.numIslands(grid) == 1

grid = [
  ['1','1','0','0','0'],
  ['0','1','0','0','1'],
  ['0','0','0','1','1'],
  ['0','0','0','0','0'],
  ['0','0','0','0','1']
]
assert s.numIslands(grid) == 3